package bat.ke.qq.com.paralle;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 并行流和串行流
 */
public class StreamApi2 {
    //需求：计算0到1亿的和
    @Test
    public void test1() {
        Instant start = Instant.now();
        long sum = 0L;
        for (long i = 0; i <= 100000000L; i++) {
            sum += i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为: " + Duration.between(start, end).toMillis());
    }

    @Test
    public void test2() {
        Instant start = Instant.now();
        ForkJoinPool fjp = new ForkJoinPool( );
        ForkJoinTask<Long> task = new ForkJoinCalculate( 0 , 100000000L ) ;
        Long sum = fjp.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println( "耗费时间为。"+Duration.between(start, end). toMillis());
    }

    @Test
    public void test3(){
        Instant start = Instant . now();
        long res = LongStream.rangeClosed(0, 100000000L).
        parallel().reduce(0,Long::sum) ;
        System.out.println(res);
        Instant end = Instant.now();
        System.out.println( "耗费时间为: "+Duration. between(start, end). toMillis());
    }

}
